﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;

public class WhoReferencedObject : Editor
{
    [MenuItem("GameObject/谁引用了对象",priority =14)]
    static void Run()
    {
        if (Selection.activeGameObject == null)
            return;

        var gameObject = Selection.activeGameObject;
        List<Object> select = new List<Object>();
        select.Add(gameObject);
        select.AddRange(gameObject.GetComponents<Component>());

        var transforms = TransformEditorHelper.SceneTransforms();
        
        List<Component> list = new List<Component>();
        List<Component> result = new List<Component>();
        int index=0;

        foreach (var transform in transforms)
        {
            EditorUtility.DisplayProgressBar("查询中", transform.name, (float)index++ / transforms.Length);
            if (transform == gameObject.transform)
                continue;
            list.Clear();
            //list.Add(transform.gameObject);
            list.AddRange(transform.GetComponents<Component>());

            foreach (var item in list)
            {
                try
                {
                    var prop = new SerializedObject(item).GetIterator();
                    while (prop.NextVisible(true))
                    {
                        if (prop.propertyType == SerializedPropertyType.ObjectReference)
                        {
                            var value = prop.objectReferenceValue;
                            if (value == null)
                                continue;

                            if (select.Contains(value))
                            {
                                result.Add(item);
                            }

                        }
                    }

                }
                catch (Exception ex)
                {
                    Debug.LogError(ex);
                }
            }
        }

        EditorUtility.ClearProgressBar();

        var window = EditorWindow.GetWindow<WhoReferencedWindow>("谁引用了对象");
        window.gameObject = gameObject;
        window.array = result.ToArray();
        window.ToString();
    }

   
}
